let accountMethod = require("../dao/accountDAO").accountMethod;
// 新增账号
exports.addAccount = function (req, res){
  // 接收新增账号传来的数据
  let newAccount = {
    userId: req.body.userId,
    superiorId: req.body.superiorId,
    accountName : req.body.accountName,
    account: req.body.account,
    accountPassword: req.body.accountPassword
  };
  // 调用账号方法中保存
  accountMethod.save(newAccount, function (err){
    if(!err){
      res.send({
        code: 200,
        msg: "新增成功！"
      });
    }else{
      res.send({
        code: 201,
        msg: "新增失败！"
      });
    }
  });
};

// 获取列表
exports.getAccountList = function (req, res){
  let userId = req.body.userId
  // 根据用户id查询列表
  accountMethod.findById(userId,function (err, doc) {
    if(!doc)
      return false;
    // 生成下级数据根据上级id
    let treeNode = function(_id, superiorId, accountName,account,accountPassword, children) {
      this._id = _id;
      this.superiorId = superiorId;
      this.accountName = accountName;
      this.account = account;
      this.accountPassword = accountPassword;
      this.children = children;
    }
    let getDFSTree = function(data, superiorId) {
      let treeList = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].superiorId == superiorId) {
          let tree = new treeNode(
              data[i]._id,
              data[i].superiorId,
              data[i].accountName,
              data[i].account,
              data[i].accountPassword,
              getDFSTree(data, data[i]._id)
          );
          treeList.push(tree)

        }
      }
      return treeList;
    }
     let tree = getDFSTree(doc, '0');
    if(!err){
      res.send({
        code: 200,
        data: tree,
        msg: "查询成功！"});
    }
    else{
      res.send({
        code: 201,
        msg: "查询失败！"});
    }
  })
};

// 删除
exports.delAccount = function (req, res){
  let id = req.body.id
  // 根据id查询单条数据
  accountMethod.findOneById(id,function (err, doc) {
    if(!err && doc){
      let par = {
        _id: id
      }
      // 删除单条数据
      accountMethod.remove(par,function (err, doc) {
        if(!err){
          res.send({
            code: 200,
            msg: "删除成功！"});
        }else{
          res.send({
            code: 200,
            msg: "删除失败！"});
        }
      })
    }
  })
};

// 修改
exports.editAccount = function (req, res) {
  let newAccount = {
    id: req.body.id,
    userId: req.body.userId,
    superiorId: req.body.superiorId,
    accountName : req.body.accountName,
    account: req.body.account,
    accountPassword: req.body.accountPassword
  };
  // 查询单个数据
  accountMethod.findOneById(newAccount.id,function (err, doc) {
    if(!err && doc){
      // 更新单个数据
      accountMethod.update({'_id':newAccount.id},newAccount,function (err) {
        if(!err){
          res.send({
            code: 200,
            msg: "修改成功！"});
        }
        else{
          res.send({
            code: 201,
            msg: "修改失败！"});
        }
      })
    }
  })
}
